#!/bin/sh
# @(#)ckdomaincf.sh	1.3	1/4/91
#
# ckdomaincf - check domain configuration
#
# SYNOPSIS
#	ckdomaincf [ -n ]
#
# ckdomaincf checks the domain configuration.  It determines which
# domains to check by examining /etc/named.boot and checking all domains
# listed on the primary and secondar lines.  However, ckdomaincf ignores
# checking the 0.0.127.in-addr.arpa domain and any domain with unixhosts
# as the data file.  It is assumed that these domain data files will
# contain domain definitions for the unix localhost and will be specific
# to the local definition.
# 
# If the -n flag is specified, no mail will be sent after checking.
# 
BOOTFILE=/etc/named.boot
MAIL=/usr/ucb/Mail
NOTIFY=hostmaster
NOTIFYLEVEL=10	# 10 - any warning or greater
		# 50 - any error or greater
		# 100 - any abort
PATH=$PATH:/usr/local/etc export PATH
TMP=/tmp/.ckd$$

set -- `getopt n $*`
if [ $? != 0 ]; then
	echo usage: ckdomaincf [ -n ]
	exit 2
fi
for i in $*; do
	case $i in
	-n ) MAIL="echo /usr/ucb/Mail"; shift;;
	--)	 shift; break;;
	esac
done

tolower() {
	echo $1 | tr A-Z a-z
}

is_in_addr() {
	if [ `expr $1 : '.*in-addr'` -gt 0 ]; then
		true;
	else
		false;
	fi
}

# strip comments from zone data
stripcomments() {
        sed -e '/^;/d' -e 's/;.*//' $*
}

# get mail address of person in charge of the zone
getpersonincharge() {
	dig soa $1. +pfset=0xa224 | \
        stripcomments | tr a-z A-Z | awk '$3 == "SOA" {print $5}'
}

# convert domain name to mail address
domaintoaddr() {
        echo $1 | sed -e 's/\.$//' -e 's/\./@/'
}

# notify the person in charge of a zone of detected errors
notifypersonincharge() {
	failtype=problems
	if [ $2 -gt 50 ]; then
		failtype=errors
	fi
	if [ $2 -gt 100 ]; then
		failtype=failures
	fi
        MB=`getpersonincharge $1`
	( cat $1.log;
	  echo ""; echo ""; echo ""; echo "Complete log of test follows:"; echo "";
	  cat log.$1.
	) | \
        $MAIL -s "$1 zone configuration $failtype" $NOTIFY `domaintoaddr $MB` 
        echo $1 zone configuration $failtype
	sed 's/^/  /' $1.log
        echo "  $NOTIFY, `domaintoaddr $MB` notified via mail."
	echo ""
}

cd /tmp

trap "rm -f $TMP*; exit 1" 2 3

egrep '^(primary|secondary)' $BOOTFILE >$TMP.domains

while read line; do
	set -- $line

	domainname=`tolower $2`
	if is_in_addr $domainname; then
		parent=arpa.
	else
		parent=
	fi

	# find data file
	while [ "$2" != "" ]; do
		shift
	done
	datafile=$1

	# ignore localhost domain stuff
	if [ $domainname = 0.0.127.in-addr.arpa -o $datafile = unixhosts ]; then
		continue
	fi

	rm -f log.$domainname.
	doc -w -e $domainname. $parent 2>/dev/null >$TMP.docout
	status=$?
	egrep -v '^(Doc-|DIGERR|Done testing)' <$TMP.docout >$domainname.log
	
	if [ $status -gt $NOTIFYLEVEL ]; then
		notifypersonincharge $domainname $status
	fi
	
	rm -f log.$domainname. $domainname.log
done <$TMP.domains

rm -f $TMP*
